package jiraworkflow

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.fields.layout.field.FieldLayout
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutManager
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.util.JiraUtils
import com.atlassian.jira.workflow.WorkflowTransitionUtil
import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl

/**
 * “评审人”点击工作流中的“审批”，当前评审人从“评审人”字段转移到“已评审”字段，
 * 当“评审人”字段为空时，表示审批完成，点击工作流中的“完成审批”
 * @author caiwl* @date 2020/4/15 10:26
 */

// 获取Jira管理器
IssueManager issueManager = ComponentAccessor.getIssueManager()
CustomFieldManager customFieldManager = ComponentAccessor.getCustomFieldManager()
FieldLayoutManager fieldLayoutManager = ComponentAccessor.getFieldLayoutManager()

// 获取登录用户
ApplicationUser user = ComponentAccessor.jiraAuthenticationContext.getLoggedInUser()
// 获取Issue
Issue issue = issueManager.getIssueObject("IPD-43")
// 获取“评审人”和“已评审”字段
CustomField approve = customFieldManager.getCustomFieldObject("customfield_10800")
Set<ApplicationUser> approvers = issue.getCustomFieldValue(approve) as Set<ApplicationUser>
CustomField approved = customFieldManager.getCustomFieldObject("customfield_10801")
Set<ApplicationUser> approvereds = issue.getCustomFieldValue(approved) as Set<ApplicationUser>
if (!approvereds) {
    approvereds = new HashSet<>()
}

// “评审人”字段移除登录用户，“已评审”加入登录用户
approvers.remove(user)
approvereds.add(user)

// 重新设置Issue的“评审人”和“已评审”字段并保存数据库
issue.setCustomFieldValue(approve, approvers)
issue.setCustomFieldValue(approved, approvereds)

FieldLayout fieldLayout = fieldLayoutManager.getFieldLayout(issue)
Map<String, ModifiedValue> modifiedFields =  issue.getModifiedFields()

FieldLayoutItem fieldLayoutItem = fieldLayout.getFieldLayoutItem(approve)
ModifiedValue modifiedValue = modifiedFields.get(approve.getId())
approve.updateValue(fieldLayoutItem, issue, modifiedValue, new DefaultIssueChangeHolder())

fieldLayoutItem = fieldLayout.getFieldLayoutItem(approved)
modifiedValue = modifiedFields.get(approved.getId())
approved.updateValue(fieldLayoutItem, issue, modifiedValue, new DefaultIssueChangeHolder())

// “评审人”为空时，完成审批
if (!approvers) {
    WorkflowTransitionUtil workflowTransitionUtil = JiraUtils.loadComponent("WorkflowTransitionUtilImpl", WorkflowTransitionUtilImpl.class)
    workflowTransitionUtil.setIssue(issue)
    workflowTransitionUtil.setUserkey(issue.getReporter().name)
    workflowTransitionUtil.setAction(31)
    workflowTransitionUtil.validate()
    workflowTransitionUtil.progress()
}

